require 'win32/registry'

def set_proxy(addr, port)
	cmd = "setx PROXY_ADDR #{addr} -m"
	system(cmd)
	if $? != 0 then return end
	cmd = "setx PROXY_PORT #{port} -m"
	system(cmd)
	if $? != 0 then return end
	cmd = "setx http_proxy http://#{addr}:#{port}"
	system(cmd)
end

def get_proxy()
	keyname = 'SYSTEM\ControlSet001\Control\Session Manager\Environment'
	access = Win32::Registry::KEY_ALL_ACCESS
	Win32::Registry::HKEY_LOCAL_MACHINE.open(keyname, access) do |reg|
		proxy_addr = reg['PROXY_ADDR']
		proxy_port = reg['PROXY_PORT']
		puts "http_proxy = http://#{proxy_addr}:#{proxy_port}"
	end
rescue
	set_proxy('proxy.ip.addr', '80')
end

def help()
	puts "proxy - set proxy Environment Variable"
	puts "usage: proxy ADDRESS [PORT]"
	puts "  ADDRESS - IP address"
	puts "  PORT    - port number (default 80)"
end

def main()
	if (ARGV.size == 0)
		get_proxy()
		return
	end
	
	if ARGV[0] == "--help"
		help()
		return
	else
		addr = ARGV[0]
		port = 80
		
		if (ARGV.size > 1)
			port = ARGV[1]
		end
		
		set_proxy(addr, port)
	end
end

main()
